package top.fullj.sysmon;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Build;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author bruce.wu
 * @date 2025/6/26 13:32
 */
class BatteryState {

    private static final Logger LOG = LoggerFactory.getLogger(BatteryState.class);

    static void grab(final Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            BatteryManager bm = (BatteryManager)context.getSystemService(Context.BATTERY_SERVICE);
            LOG.info("battery.isCharging={}", bm.isCharging());
        }
    }

    static void start(final Context context) {
        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        context.registerReceiver(receiver, filter);
    }

    static void stop(final Context context) {
        context.unregisterReceiver(receiver);
    }

    private static final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
            boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                    status == BatteryManager.BATTERY_STATUS_FULL;

            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            float batteryPct = level * 100 / (float)scale;

            LOG.info("{}: isCharging={}, battery={}%", intent.getAction(), isCharging, batteryPct);
        }
    };

}
